package org.platform.processor.diagnose;

import org.platform.constant.ExecutorStatus;
import org.platform.core.JobManager;
import org.platform.dao.mapper.FdTimingDiagnoseStrategyMapper;
import org.platform.mo.db.FdTimingDiagnoseStrategy;
import org.platform.processor.diagnose.job.AddTestDiagnoseJob;
import org.quartz.JobKey;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.JobDetailImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;

/**
 * 用于创建定时器
 * 1.创建定时诊断
 * 2.系统启动的时候自动检测未执行/未执行完毕的定时器{@link TimingTaskStrategyProcessor#initTiming()}
 *
 * @author FengJie
 * @date 2018/8/18
 */
@Service
public class TimingTaskStrategyProcessor {
    @Autowired
    private JobManager job;
    @Autowired
    private FdTimingDiagnoseStrategyMapper strategyMapper;

    /**
     * 新建定时任务
     *
     * @param startTime   开始时间
     * @param entTime     结束时间
     * @param cycle       间隔周期
     * @param count       执行总次数
     * @param id          key
     */
    public void addTiming(Long startTime, Long entTime, Integer cycle, Integer count, String id) {
        JobDetailImpl jd = new JobDetailImpl();
        jd.setJobClass(AddTestDiagnoseJob.class);
        jd.setKey(JobKey.jobKey(id));
        jd.getJobDataMap().put(AddTestDiagnoseJob.ID, id);

        SimpleScheduleBuilder builder = SimpleScheduleBuilder
                .simpleSchedule()
                .withIntervalInSeconds(cycle);
        //避免执行次数为0 的情况
        if (count != 0) {
            builder.withRepeatCount(count);
        }

        SimpleTrigger trigger = TriggerBuilder.newTrigger()
                .withSchedule(builder)
                .startAt(new Date(startTime))
                .endAt(new Date(entTime))
                .build();

        job.register(jd, trigger);
    }

    /**
     * 删除定时任务
     *
     * @param jobKey
     */
    public void delTiMing(String jobKey) {
        JobDetailImpl jd = new JobDetailImpl();
        jd.setKey(JobKey.jobKey(jobKey));
        job.unRegister(jd);
    }

    /**
     * 系统初始化,检测未执行完成的任务
     */
    @PostConstruct
    void initTiming() {
        Example example = new Example(FdTimingDiagnoseStrategy.class);
        example.createCriteria().andNotEqualTo("executorStatus", ExecutorStatus.completed.getValue());
        List<FdTimingDiagnoseStrategy> strategyList = strategyMapper.selectByExample(example);
        strategyList.forEach(list ->
                this.addTiming(
                        list.getStartTime(),
                        list.getEndTime(),
                        list.getCycle(),
                        list.getCount(),
                        list.getId()
                )
        );
    }
}
